import { useEffect, useState, type RefObject } from 'react'
import style from './RecepFormStyle.module.sass'
import { Button, DatePicker, Ellipsis, Form, Input, Picker, Selector, Stepper, type DatePickerRef, type PickerRef } from 'antd-mobile'
import dayjs from 'dayjs'
import { useLocation, useNavigate } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { setReceptionInfo } from '../../../../../../store/ReceptionSlice'
import type { HomeViewSlice } from '../../../../../../type/HomeViewSlice'
import type { ReceptionSlice } from '../../../../../../type/ReceptionSlice'
import { AddOutline } from 'antd-mobile-icons'
import Hobby from '../../../hobby/Hobby'
import { clearCustomerData } from '../../../../../../store/CustomerSlice'
import type { CustomerData } from '../../../../../../type/CustomerState'

function RecepForm() {

  // #region 变量声明
  const navigate = useNavigate()
  const { mapData } = useSelector((state: { homeView: HomeViewSlice }) => state.homeView)
  const { receptionInfo } = useSelector((state: { reception: ReceptionSlice }) => state.reception)
  const { customer } = useSelector((state: { customer: { customer: CustomerData[] } }) => state.customer);
  console.log(customer)
  const dispatch = useDispatch()
  const [form] = Form.useForm()
  const location = useLocation()
  const [forceUpdate, setForceUpdate] = useState(false)
  // #endregion
  // #region 函数
  function ValueChangeHandler() {
    if (!form) return
    const formValue = { ...form.getFieldsValue() }
    const time = {
      start: formValue.start?.getTime(),
      end: formValue.end?.getTime(),
    }
    Reflect.deleteProperty(formValue, 'start')
    Reflect.deleteProperty(formValue, 'end')
    dispatch(setReceptionInfo({ ...formValue, time }))
    // dispatch(saveCustomerData(customer))
    // console.log(form.getFieldValue('start'), dayjs(form.getFieldValue('start')).add(1, 'weeks').toString())
    console.log({ ...formValue, time })
  }
  // #endregion

  // #region Hooks
  useEffect(() => {
    if (!form) return
    if (location.state && !location.state.new) {
      const formValue: Omit<ReceptionSlice['receptionInfo'], 'time'> & { time?: { start?: number, end?: number } } = { ...receptionInfo }
      const { start, end } = receptionInfo.time
      delete formValue.time
      console.log({
        ...formValue,
        start: dayjs(start),
        end: dayjs(end),
      })
      form.setFieldsValue({
        ...formValue,
        start: start && new Date(start),
        end: end && new Date(end),
      })
      setForceUpdate(!forceUpdate)
      // console.log(form.getFieldValue('start'))
    } else {
      dispatch(clearCustomerData([]))
    }
    // eslint-disable-next-line
  }, [location])
  // #endregion

  return (
    <div className='recep_form'>
      <Form className={style.form} form={form} layout='horizontal' onValuesChange={ValueChangeHandler}>
        {mapData.city && <Form.Item name='address' label='接待地点'
          required
          rules={[{ required: true, message: '接待地点不能为空!' }]}
        >
          <Selector
            columns={3}
            multiple
            options={mapData.city.map(v => ({ label: v.name, value: v.code }))}
          />
        </Form.Item>}
        <Form.Item name='start' label='接待时间'
          rules={[{ required: true, message: '开始时间不能为空' }]}
          trigger='onConfirm'
          onClick={(_, datePickerRef: RefObject<DatePickerRef>) => {
            datePickerRef.current?.open()
          }}
        >
          <DatePicker precision='second' title='开始时间'>
            {value => value
              ? dayjs(value).format('YYYY-MM-DD hh:mm:ss')
              : <div style={{ color: '#cccccc' }}>开始日期</div>}
          </DatePicker>
        </Form.Item>

        <Form.Item name='end' label
          disabled={form.getFieldValue('start') === undefined}
          required={false}
          rules={[{ required: true, message: '结束时间不能为空' }]}
          trigger='onConfirm'
          onClick={(_, datePickerRef: RefObject<DatePickerRef>) => {
            datePickerRef.current?.open()
          }
          }
        >
          <DatePicker
            precision='second'
            title='结束时间'
            min={form.getFieldValue('start')}
            max={form.getFieldValue('start') && dayjs(form.getFieldValue('start')).add(1, 'weeks').toDate()}
          >
            {value =>
              value ? dayjs(value).format('YYYY-MM-DD hh:mm:ss') : <div style={{ color: '#cccccc' }}>结束日期</div>
            }
          </DatePicker>
        </Form.Item>

        {mapData.receptionCategory && <Form.Item name='type' label='接待类别'
          required
          trigger='onConfirm'
          rules={[{ required: true, message: '接待类别不能为空' }]}
          onClick={(_, pickerRef: RefObject<PickerRef>) => {
            pickerRef.current?.open()
          }
          }
        >
          <Picker title='接待类别' columns={[mapData.receptionCategory.map(v => ({ label: v.label, value: v.value }))]}>{
            (value) => value.every(item => item === null)
              ? <div className={style.form_white_color}>未选择</div>
              : <Ellipsis direction='end' rows={2} content={value.map(item => item?.label ?? '未选择').join(' - ')} />
          }</Picker>
        </Form.Item>}

        {mapData.photoNotSupportShowrooms && <Form.Item label='来访单位' required name='company'
          rules={[{ required: true, message: '来访单位不能为空' }]}
        >
          <Input placeholder='请输入单位名称' />
        </Form.Item>}

        <Form.Item name='numberOfPeople' label='来访数量' required childElementPosition='right'
          rules={[{ required: true, message: '来访数量不能为空' }]}
        >
          <Stepper />
        </Form.Item>

        <Form.Item name='objective' label='来访目的' required childElementPosition='right'
          rules={[{ required: true, message: '来访目的不能为空' }]}
        >
          <Input placeholder='请输入来访目的' />
        </Form.Item>

        <Form.Item name='importantCustomerPreferences' label='重要客户喜好&禁忌' required childElementPosition='right'>
          <Button size='small' color='primary' fill='outline' onClick={() => navigate('/customer')}><AddOutline />添加</Button>
        </Form.Item>

        <Form.Item name='hobby'>
          <Hobby item={customer} />
        </Form.Item>

        <Form.Item name='entourage' label='陪同人员' required childElementPosition='right'
          rules={[{ required: true, message: '陪同人员不能为空' }]}
        >
          <Stepper />
        </Form.Item>

        <Form.Item name='visitingVehicles' label='来访车辆' required childElementPosition='right'
          rules={[{ required: true, message: '来访车辆不能为空' }]}
        >
          <Stepper />
        </Form.Item>
      </Form>
    </div>
  )
}

export default RecepForm

